#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cbm.h>

#include "Buffers.h"
#include "Trim.h"
#include "Splitter.h"
#include "Dispatcher.h"
#include "Drives.h"

#pragma code-name("DELCODE");
#pragma rodata-name("DELCODE");

unsigned char deleteFile(unsigned char driveIndex)
{
	unsigned char r = 0, i = 0;
	unsigned int count = 0,track = 0, sector = 0;
	int result = 0;
	drive_t *drive = &drives[driveIndex];
	static char buffer[256];
	tokenCollection_t *collection = NULL;
	parsedPath_t *path = NULL;
	
	strcpy(buffer, buffer3);

	collection = splitString(buffer);

	if(collection->count != 2)
	{
		printf("\nusage: del :file\n");
		free(collection);
		return 0;
	}

	path = parsePath(1, collection, driveIndex);

	driveIndex = getDrive(path->device);
	if(driveIndex == 0xFF) 
	{
		printf("\nUnknown device.");
		free(collection);
		free(path);
		return 1;
	}
	drive = &drives[driveIndex];

	memset(arguments, 0, sizeof(arguments));

	if(drive->type == CBM15x1)
	{
		sprintf(buffer3, "s%1u:%s", path->drive, path->file);
	}
	else
	{
		if(drive->type == VICE)
		{
			sprintf(buffer3, "cd:%s", path->path);
		}
		else
		{
			sprintf(buffer3, "cd%s", path->path);
		}
		if(executeCommand(drive, buffer3, 0))
		{
			memset(buffer3, 0, sizeof(buffer3));
			sprintf(buffer3, "s%1u:%s", path->drive, path->file);
		}
		else
		{
			printf("\nCould not change directory.");
			free(collection);
			free(path);
			return 1;
		}
	}

	r = cbm_open(15, path->device, 15, buffer3);
	memset(buffer2, 0, sizeof(buffer2));
	result = cbm_read(15, buffer2, sizeof(buffer2));
	cbm_close(15);
	sscanf(buffer2, "%d,%s,%d,%d", &count, buffer3, &track, &sector);

	r = 0;
	if(count == 1)
	{
		printf("\nFiles deleted.", count);
	}
	else
	{
		printf("\nNo matching files.");
	}
	free(collection);
	free(path);
	return r;
}
